package cn.ratel.route;

import cn.ratel.component.Handlers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public enum DefaultHandlers implements Handlers.Handler {

	RENDERING_TIME {
		@Override
		public void handle(HandlerContext handlerContext) {
			long start = System.currentTimeMillis();
			handlerContext.next();
			long end = System.currentTimeMillis();
			log.debug("time total: [{}] , {} ms", handlerContext.getUri(), end - start);
		}
	},

	CONTEXT_THREAD_LOCAL {
		@Override
		public void handle(HandlerContext handlerContext) {
			Map<String, String[]> params = handlerContext.getRequest().getParameterMap();

			ContextHolder.getUri().set(handlerContext.getUri());
			ContextHolder.getParameterMap().set(params);

			Map<String, Map<String, String>> modelAttrMap = new HashMap<>();
			for (Map.Entry<String, String[]> param : params.entrySet()) {
				int i = param.getKey().indexOf('.');
				if (i == -1) {
					continue;
				}
				String[] values = param.getValue();
				if (values == null) {
					continue;
				}
				String modelName = param.getKey().substring(0, i);
				Map<String, String> modelAttrs = modelAttrMap.get(modelName);
				if (modelAttrs == null) {
					modelAttrs = new HashMap<>();
				}
				modelAttrs.put(param.getKey().substring(i + 1), values[0]);
				modelAttrMap.put(modelName, modelAttrs);
			}
			ContextHolder.getModelAttrMap().set(modelAttrMap);
			ContextHolder.getRequest().set(handlerContext.getRequest());
			ContextHolder.getResponse().set(handlerContext.getResponse());

			handlerContext.next();

			ContextHolder.getUri().remove();
			ContextHolder.getParameterMap().remove();
			ContextHolder.getModelAttrMap().remove();
			ContextHolder.getRequest().remove();
			ContextHolder.getResponse().remove();
		}
	};

	private static final Logger log = LoggerFactory.getLogger(DefaultHandlers.class);
}